<template>
  <div class="inventory-count-create">
    <el-page-header content="新增盘点" @back="router.back" style="margin-bottom: 16px" />

    <!-- 基础信息 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span style="font-size: 35px">基础信息</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" label-width="auto" style="max-width: 1000px">
        <el-container>
          <el-aside width="500px">
            <el-form-item label="盘点单号">
              <el-input
                v-model="form.inventoryCountCode"
                placeholder="自动获取系统编号"
                class="readonly-input"
                readonly
              >
                <template #append>
                  <el-button @click="generateCode" :loading="generatingCode">
                    自动生成
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="盘点类型">
              <el-select v-model="form.countTypeId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in countTypeOptions"
                  :key="item.countTypeId"
                  :label="item.countTypeName"
                  :value="item.countTypeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="盘点开始时间">
              <el-date-picker
                v-model="form.countStartTime"
                type="date"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择"
                style="width: 100%"
                @change="handleWarehouseChange"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
              <el-button
                v-if="form.warehouseId"
                size="small"
                style="margin-top: 8px"
                @click="handleLockWarehouse"
              >
                设置
              </el-button>
            </el-form-item>
            <el-form-item label="经办人">
              <el-input
                v-model="selectedHandlerName"
                placeholder="请选择经办人"
                readonly
                style="cursor: pointer"
                @click="openUserDialog"
              >
                <template #append>
                  <el-button icon="Search" @click="openUserDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-aside>

          <el-aside width="500px">
            <el-form-item label="盘点结束时间" style="margin-left: 28px">
              <el-date-picker
                v-model="form.countEndTime"
                type="date"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="备注" style="margin-left: 28px">
              <el-input
                v-model="form.remarks"
                type="textarea"
                placeholder="请输入"
                :rows="4"
              />
            </el-form-item>
            
          </el-aside>
        </el-container>
      </el-form>
    </el-card>

    <!-- 盘点明细 -->
    <el-card shadow="never" style="margin-top: 16px">
      <template #header>
        <div class="card-header">
          <span style="font-size: 35px">盘点明细</span>
          <el-space>
            <el-button type="primary" @click="openProductDialog">添加</el-button>
            <el-button @click="handleRemoveSelected">移除</el-button>
            <el-button @click="handleImport">导入</el-button>
          </el-space>
        </div>
      </template>

      <!-- 提示信息 -->
      <div v-if="!form.warehouseId" class="warning-message">
        <el-icon><Warning /></el-icon>
        <span>请选择仓库!</span>
      </div>
      <div v-if="details.length === 0" class="warning-message">
        <el-icon><Warning /></el-icon>
        <span>请选择货品!</span>
      </div>

      <!-- 盘点明细表格 -->
      <el-table
        :data="details"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" width="120" />
        <el-table-column prop="productCode" label="货品编号" width="120" />
        <el-table-column prop="specificationModel" label="规格型号" width="120" />
        <el-table-column prop="unitName" label="单位" width="100" />
        <el-table-column prop="productTypeName" label="货品类型" width="100" />
        <el-table-column prop="bookedInventory" label="账面库存" width="120" align="right" />
        <el-table-column prop="bookedAmount" label="账面金额" width="120" align="right">
          <template #default="scope">
            ¥{{ Number(scope.row.bookedAmount || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="storageLocationId" label="盘点库位" width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.storageLocationId"
              placeholder="请选择"
              size="small"
              style="width: 100%"
              :disabled="!form.warehouseId"
            >
              <el-option
                v-for="loc in storageLocationOptions"
                :key="loc.storagelocationId"
                :label="loc.storagelocationName"
                :value="loc.storagelocationId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="countQuantity" label="盘点数量" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.countQuantity"
              :min="0"
              size="small"
              :controls="false"
              style="width: 100%"
              @change="calculateProfitLoss(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="profitLossQuantity" label="盈亏数量" width="120" align="right">
          <template #default="scope">
            <span :style="{ color: scope.row.profitLossQuantity > 0 ? '#67c23a' : scope.row.profitLossQuantity < 0 ? '#f56c6c' : '' }">
              {{ scope.row.profitLossQuantity || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="countStatus" label="盘点状态" width="100">
          <template #default="scope">
            <el-tag
              :type="getCountStatusType(scope.row.countStatus)"
              size="small"
            >
              {{ getCountStatusText(scope.row.countStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计行 -->
      <div class="summary-info">
        <span>合计：</span>
        <span style="margin-left: 20px">账面库存：{{ totalBookedInventory }}</span>
        <span style="margin-left: 20px">账面金额：¥{{ totalBookedAmount.toFixed(2) }}</span>
        <span style="margin-left: 20px">盘点数量：{{ totalCountQuantity }}</span>
        <span style="margin-left: 20px">盘盈数量：<span style="color: #67c23a">{{ totalGainQuantity }}</span></span>
        <span style="margin-left: 20px">盘亏数量：<span style="color: #f56c6c">{{ totalLossQuantity }}</span></span>
        <span style="margin-left: 20px">盘盈金额：<span style="color: #67c23a">¥{{ totalGainAmount.toFixed(2) }}</span></span>
        <span style="margin-left: 20px">盘亏金额：<span style="color: #f56c6c">¥{{ totalLossAmount.toFixed(2) }}</span></span>
      </div>
    </el-card>

    <!-- 底部按钮 -->
    <el-card>
      <div style="text-align: right; margin-top: 16px">
        <el-button @click="handleClose">关闭</el-button>
        <el-button @click="handleSaveDraft">保存为草稿</el-button>
        <el-button type="success" @click="handleSave" :loading="saving">保存</el-button>
      </div>
    </el-card>

    <!-- 货品选择对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="选择货品"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="productSearchForm" :inline="true" class="search-form">
        <el-form-item label="货品名称">
          <el-input
            v-model="productSearchForm.productName"
            placeholder="请输入货品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchProducts" icon="Search">查询</el-button>
          <el-button @click="resetProductSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="productList"
        style="width: 100%"
        @selection-change="handleProductSelection"
        v-loading="productTableLoading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" width="120" />
        <el-table-column prop="productCode" label="货品编号" width="120" />
        <el-table-column prop="producttypeName" label="货品类型" width="100" />
        <el-table-column prop="productspecification" label="规格型号" width="120" />
        <el-table-column prop="productUnit" label="单位" width="80" />
        <el-table-column prop="inventoryCurrtnumber" label="当前库存" width="100" />
      </el-table>

      <div class="pagination-container" style="margin-top: 12px">
        <el-pagination
          v-model:current-page="productPagination.pageindex"
          v-model:page-size="productPagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="productPagination.total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleProductSizeChange"
          @current-change="handleProductCurrentChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection" :disabled="selectedProducts.length === 0">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 经办人选择对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      title="选择人员"
      width="70%"
      :close-on-click-modal="false"
    >
      <div class="user-selection-container">
        <div class="search-section">
          <el-input
            v-model="userSearchKeyword"
            placeholder="请输入姓名或编号"
            clearable
            style="width: 300px; margin-right: 10px;"
          />
          <el-button type="primary" @click="searchUsers" icon="Search">查询</el-button>
        </div>

        <div class="content-section">
          <div class="organization-tree">
            <div class="tree-header">组织架构</div>
            <el-tree
              :data="organizationTree"
              :props="treeProps"
              node-key="organizationId"
              @node-click="handleOrganizationClick"
              :expand-on-click-node="false"
              :highlight-current="true"
              v-loading="treeLoading"
            >
              <template #default="{ data }">
                <span class="tree-node">{{ data.organizationName || data.label }}</span>
              </template>
            </el-tree>
          </div>

          <div class="user-list">
            <div class="list-header">
              已选择 {{ selectedUser ? 1 : 0 }} 人
              <el-tag
                v-if="selectedUser"
                closable
                @close="clearSelectedUser"
                class="selected-user-tag"
              >
                {{ selectedUser.userName }}
              </el-tag>
            </div>
            <div class="user-grid" v-loading="userLoading">
              <div
                v-for="user in filteredUsers"
                :key="user.userId"
                :class="['user-item', { selected: selectedUser && selectedUser.userId === user.userId }]"
                @click="selectUser(user)"
              >
                <div class="user-avatar">{{ user.userName?.charAt(0) }}</div>
                <div class="user-info">
                  <div class="user-name">{{ user.userName }}</div>
                  <div class="user-account">{{ user.userAccount }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUserSelection" :disabled="!selectedUser">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'

const router = useRouter()
const route = useRoute()

const getCurrentUserName = () => {
  if (typeof window === 'undefined') return ''
  return (
    localStorage.getItem('userName') ||
    localStorage.getItem('UserName') ||
    localStorage.getItem('accountName') ||
    ''
  )
}

const formRef = ref()
const form = reactive({
  inventoryCountId: '',
  inventoryCountCode: '',
  countTypeId: '',
  countStartTime: null as Date | string | null,
  countEndTime: null as Date | string | null,
  warehouseId: '',
  handlerId: '',
  remarks: '',
  checkPreparer: '张三',
  checkPreparetime: new Date() as Date | string | null,
})

const details = ref<any[]>([])
const selectedDetails = ref<any[]>([])
const saving = ref(false)
const generatingCode = ref(false)

const countTypeOptions = ref<any[]>([])
const warehouseOptions = ref<any[]>([])
const storageLocationOptions = ref<any[]>([])

// 货品选择对话框
const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<any[]>([])
const selectedProducts = ref<any[]>([])
const productSearchForm = reactive({
  productName: '',
})
const productPagination = reactive({
  pageindex: 1,
  pagesize: 10,
  total: 0,
})

// 经办人选择对话框
const userDialogVisible = ref(false)
const userSearchKeyword = ref('')
const userLoading = ref(false)
const treeLoading = ref(false)
const allUsers = ref<any[]>([])
const filteredUsers = ref<any[]>([])
const organizationTree = ref<any[]>([])
const currentOrganizationId = ref<number | null>(null)
const selectedUser = ref<any>(null)
const selectedHandlerName = ref('')

const treeProps = {
  children: 'children',
  label: 'label',
}

// 编号生成
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY':
          return String(now.getFullYear())
        case 'YY':
          return String(now.getFullYear()).slice(-2)
        case 'MM':
          return pad(now.getMonth() + 1)
        case 'DD':
          return pad(now.getDate())
        case 'HH':
          return pad(now.getHours())
        case 'MI':
          return pad(now.getMinutes())
        case 'SS':
          return pad(now.getSeconds())
        default:
          return ''
      }
    })
    .join('')
  const serialLength = Number(rule?.serialLength ?? 3)
  const serial = '1'.padStart(serialLength > 0 ? serialLength : 3, '0')
  return `${rule?.codePrefix || ''}${timePart}${serial}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetName },
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  } catch (err: any) {
    console.error(`[numbering] 获取编号规则失败 (${targetName})`, err)
    throw new Error(err?.message || '获取编号规则失败，请先配置编号规则')
  }
}

const generateCode = async () => {
  if (generatingCode.value) return
  generatingCode.value = true
  try {
    form.inventoryCountCode = await requestNumber('InventoryCount', '盘点单')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    ElMessage.error(error?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

// 加载盘点类型
const loadCountTypes = async () => {
  try {
    const res = await myaxios.get('/api/InventoryCount/GetCountType')
    if (res.data?.success || res.data?.code === 200) {
      countTypeOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取盘点类型失败:', error)
  }
}

// 加载仓库列表
const loadWarehouses = async () => {
  try {
    const res = await myaxios.get('/api/Warehousing/GetWarehouse')
    if (res.data?.success || res.data?.code === 200) {
      warehouseOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 加载库位列表
const loadStorageLocations = async () => {
  if (!form.warehouseId) {
    storageLocationOptions.value = []
    return
  }
  try {
    const res = await myaxios.get('/api/Warehouse/GetStoragelocation', {
      params: {
        warehouseId: form.warehouseId,
        storagelocationstate: 1,
        pageindex: 1,
        pagesize: 1000,
      },
    })
    if (res.data?.success || res.data?.code === 200) {
      storageLocationOptions.value = res.data.data?.data || []
    }
  } catch (error) {
    console.error('获取库位列表失败:', error)
  }
}

const handleWarehouseChange = () => {
  loadStorageLocations()
}

const handleLockWarehouse = () => {
  ElMessage.info('锁定仓库功能待实现')
}

// 货品选择
const openProductDialog = () => {
  if (!form.warehouseId) {
    ElMessage.warning('请先选择仓库')
    return
  }
  productDialogVisible.value = true
  searchProducts()
}

const searchProducts = async () => {
  productTableLoading.value = true
  try {
    const res = await myaxios.get('/api/Product/GetProduct', {
      params: {
        Pageindex: productPagination.pageindex,
        PageSize: productPagination.pagesize,
        ProductName: productSearchForm.productName,
        number: 1,
      },
    })
    if (res.data?.success || res.data?.code === 200) {
      const payload = res.data.data || {}
      productList.value = payload.data || payload.items || []
      productPagination.total = payload.listCount || productList.value.length || 0
    }
  } catch (error) {
    console.error('搜索货品失败:', error)
    ElMessage.error('搜索货品失败')
  } finally {
    productTableLoading.value = false
  }
}

const resetProductSearch = () => {
  productSearchForm.productName = ''
  productPagination.pageindex = 1
  searchProducts()
}

const handleProductSelection = (selection: any[]) => {
  selectedProducts.value = selection
}

const handleProductSizeChange = (val: number) => {
  productPagination.pagesize = val
  productPagination.pageindex = 1
  searchProducts()
}

const handleProductCurrentChange = () => {
  searchProducts()
}

const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择至少一个货品')
    return
  }

  let addedCount = 0
  selectedProducts.value.forEach((product) => {
    const exists = details.value.find((item) => item.productId === product.productId)
    if (!exists) {
      // 获取当前库存
      const currentStock = product.inventoryCurrtnumber || 0
      const unitPrice = product.productInmoney || 0
      const bookedAmount = currentStock * unitPrice

      details.value.push({
        productId: product.productId,
        productName: product.productName,
        productCode: product.productCode,
        specificationModel: product.productspecification || '',
        unitName: product.productUnit || '',
        productTypeName: product.producttypeName || '',
        bookedInventory: currentStock,
        bookedAmount: bookedAmount,
        storageLocationId: null,
        countQuantity: currentStock, // 默认盘点数量等于账面库存
        profitLossQuantity: 0,
        countStatus: 0, // 0-无盈亏, 1-盘盈, 2-盘亏
        referenceUnitPrice: unitPrice,
        profitLossAmount: 0,
      })
      addedCount++
    }
  })

  productDialogVisible.value = false
  selectedProducts.value = []
  if (addedCount > 0) {
    ElMessage.success(`成功添加 ${addedCount} 个货品`)
  } else {
    ElMessage.warning('所选货品已存在于盘点明细中')
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedDetails.value = selection
}

const handleRemoveSelected = () => {
  if (selectedDetails.value.length === 0) {
    ElMessage.warning('请选择需要移除的明细')
    return
  }
  const selectedIds = selectedDetails.value.map((item) => item.productId)
  details.value = details.value.filter((item) => !selectedIds.includes(item.productId))
  ElMessage.success('移除成功')
}

const removeDetail = (index: number) => {
  details.value.splice(index, 1)
  ElMessage.success('移除成功')
}

const calculateProfitLoss = (row: any) => {
  const bookedInventory = Number(row.bookedInventory || 0)
  const countQuantity = Number(row.countQuantity || 0)
  row.profitLossQuantity = countQuantity - bookedInventory

  // 计算盈亏金额
  const unitPrice = Number(row.referenceUnitPrice || 0)
  row.profitLossAmount = row.profitLossQuantity * unitPrice

  // 更新盘点状态
  if (row.profitLossQuantity > 0) {
    row.countStatus = 1 // 盘盈
  } else if (row.profitLossQuantity < 0) {
    row.countStatus = 2 // 盘亏
  } else {
    row.countStatus = 0 // 无盈亏
  }
}

const getCountStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

const getCountStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '无盈亏'
    case 1:
      return '盘盈'
    case 2:
      return '盘亏'
    default:
      return '未知'
  }
}

// 合计计算
const totalBookedInventory = computed(() => {
  return details.value.reduce((sum, item) => sum + Number(item.bookedInventory || 0), 0)
})

const totalBookedAmount = computed(() => {
  return details.value.reduce((sum, item) => sum + Number(item.bookedAmount || 0), 0)
})

const totalCountQuantity = computed(() => {
  return details.value.reduce((sum, item) => sum + Number(item.countQuantity || 0), 0)
})

const totalGainQuantity = computed(() => {
  return details.value.reduce(
    (sum, item) => sum + (item.profitLossQuantity > 0 ? item.profitLossQuantity : 0),
    0,
  )
})

const totalLossQuantity = computed(() => {
  return details.value.reduce(
    (sum, item) => sum + (item.profitLossQuantity < 0 ? Math.abs(item.profitLossQuantity) : 0),
    0,
  )
})

const totalGainAmount = computed(() => {
  return details.value.reduce(
    (sum, item) => sum + (item.profitLossAmount > 0 ? item.profitLossAmount : 0),
    0,
  )
})

const totalLossAmount = computed(() => {
  return details.value.reduce(
    (sum, item) => sum + (item.profitLossAmount < 0 ? Math.abs(item.profitLossAmount) : 0),
    0,
  )
})

// 经办人选择
const openUserDialog = () => {
  userDialogVisible.value = true
  loadOrganizations()
  loadAllUsers()
}

const loadOrganizations = async () => {
  treeLoading.value = true
  try {
    const res = await myaxios.get('/api/Organization/GetOrganizationTree', {
      params: { parentid: 0 },
    })
    if (Array.isArray(res.data)) {
      organizationTree.value = transformOrganizationTree(res.data)
    }
  } catch (error) {
    console.error('获取组织架构失败:', error)
  } finally {
    treeLoading.value = false
  }
}

const transformOrganizationTree = (nodes: any[]): any[] =>
  nodes.map((node) => ({
    organizationId: node.id,
    organizationName: node.label,
    parentId: node.parentId,
    children: node.children ? transformOrganizationTree(node.children) : [],
  }))

const loadAllUsers = async () => {
  userLoading.value = true
  try {
    const res = await myaxios.get('/api/Supplier/GetUser')
    if (res.data?.success || res.data?.code === 200) {
      allUsers.value = res.data.data || []
      filteredUsers.value = allUsers.value
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    userLoading.value = false
  }
}

const handleOrganizationClick = (data: any) => {
  const orgId = data.organizationId || data.id
  currentOrganizationId.value = orgId
  filterUsersByOrganization(orgId)
}

const filterUsersByOrganization = (orgId: number) => {
  if (orgId) {
    filteredUsers.value = allUsers.value.filter((user) => user.organizationId === orgId)
  } else {
    filteredUsers.value = allUsers.value
  }
  if (userSearchKeyword.value) {
    applySearchFilter()
  }
}

const searchUsers = () => {
  applySearchFilter()
}

const applySearchFilter = () => {
  let users = currentOrganizationId.value
    ? allUsers.value.filter((user) => user.organizationId === currentOrganizationId.value)
    : allUsers.value

  if (userSearchKeyword.value) {
    const keyword = userSearchKeyword.value.toLowerCase()
    users = users.filter(
      (user) =>
        user.userName?.toLowerCase().includes(keyword) ||
        user.userAccount?.toLowerCase().includes(keyword),
    )
  }

  filteredUsers.value = users
}

const selectUser = (user: any) => {
  selectedUser.value = user
}

const clearSelectedUser = () => {
  selectedUser.value = null
}

const confirmUserSelection = () => {
  if (!selectedUser.value) {
    ElMessage.warning('请选择经办人')
    return
  }
  form.handlerId = String(selectedUser.value.userId)
  selectedHandlerName.value = selectedUser.value.userName || ''
  userDialogVisible.value = false
  selectedUser.value = null
  userSearchKeyword.value = ''
  currentOrganizationId.value = null
  ElMessage.success('经办人选择成功')
}

// 保存
const handleSave = async () => {
  if (saving.value) return
 
  if (!form.warehouseId) {
    ElMessage.warning('请选择仓库')
    return
  }
  if (details.value.length === 0) {
    ElMessage.warning('请添加盘点明细')
    return
  }

  if (!form.checkPreparer) {
    form.checkPreparer = selectedHandlerName.value || getCurrentUserName() || '系统'
  }
  if (!form.checkPreparetime) {
    form.checkPreparetime = new Date()
  }

  saving.value = true
  try {
    const payload = {
      inventoryCountId: form.inventoryCountId || undefined,
      inventoryCountCode: form.inventoryCountCode,
      countTypeId: Number(form.countTypeId) || 0,
      countStartTime: form.countStartTime
        ? moment(form.countStartTime).format('YYYY-MM-DD')
        : moment().format('YYYY-MM-DD'),
      countEndTime: form.countEndTime
        ? moment(form.countEndTime).format('YYYY-MM-DD')
        : moment().format('YYYY-MM-DD'),
      warehouseId: Number(form.warehouseId) || 0,
      handlerId: Number(form.handlerId) || 0,
      remarks: form.remarks || '',
      checkPreparer: form.checkPreparer || '',
      checkPreparetime: form.checkPreparetime
        ? moment(form.checkPreparetime).format('YYYY-MM-DD HH:mm:ss')
        : moment().format('YYYY-MM-DD HH:mm:ss'),
      detailList: details.value.map((item) => ({
        productId: item.productId,
        bookedInventory: Number(item.bookedInventory || 0),
        bookedAmount: Number(item.bookedAmount || 0),
        storageLocationId: Number(item.storageLocationId) || 0,
        countQuantity: Number(item.countQuantity || 0),
        profitLossQuantity: Number(item.profitLossQuantity || 0),
        profitLossAmount: Number(item.profitLossAmount || 0),
        referenceUnitPrice: Number(item.referenceUnitPrice || 0),
      })),
    }

    const url = form.inventoryCountId
      ? '/api/InventoryCount/UpdateInventoryCount'
      : '/api/InventoryCount/CreateInventoryCount'
    const method = form.inventoryCountId ? 'put' : 'post'

    const res = await myaxios({ url, method, data: payload } as any)

    if (res.data?.success || res.data?.code === 200) {
      ElMessage.success('保存成功')
      router.push('/GetInventoryCount')
    } else {
      ElMessage.error(res.data?.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error?.response?.data?.message || error?.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

const handleSaveDraft = async () => {
  // 保存为草稿，状态为0
  await handleSave()
}

const handleImport = () => {
  ElMessage.info('导入功能待实现')
}

const handleClose = () => {
  router.back()
}

onMounted(() => {
  loadCountTypes()
  loadWarehouses()
  if (route.query.inventoryCountId) {
    loadForEdit(Number(route.query.inventoryCountId))
  }
})

const loadForEdit = async (inventoryCountId: number) => {
  try {
    const res = await myaxios.get('/api/InventoryCount/GetInventoryCountDetail', {
      params: { inventoryCountId },
    })
    if (res.data?.success || res.data?.code === 200) {
      const data = res.data.data || {}
      form.inventoryCountId = String(data.inventoryCountId)
      form.inventoryCountCode = data.inventoryCountCode || ''
      form.countTypeId = data.countTypeId || ''
      form.countStartTime = data.countStartTime ? new Date(data.countStartTime) : null
      form.countEndTime = data.countEndTime ? new Date(data.countEndTime) : null
      form.warehouseId = String(data.warehouseId || '')
      form.handlerId = String(data.handlerId || '')
      form.remarks = data.remarks || ''
      form.checkPreparer = data.documentCreator || data.checkPreparer || ''
      form.checkPreparetime = data.documentCreation ? new Date(data.documentCreation) : null
      selectedHandlerName.value = data.handlerName || ''
      details.value = (data.detailList || []).map((item: any) => ({
        productId: item.productId,
        productName: item.productName || '',
        productCode: item.productCode || '',
        specificationModel: item.specificationModel || '',
        unitName: item.unitName || '',
        productTypeName: item.productTypeName || '',
        bookedInventory: item.bookedInventory || 0,
        bookedAmount: item.bookedAmount || 0,
        storageLocationId: item.storageLocationId || null,
        countQuantity: item.countQuantity || 0,
        profitLossQuantity: item.profitLossQuantity || 0,
        countStatus: item.countStatus || 0,
        referenceUnitPrice: item.referenceUnitPrice || 0,
        profitLossAmount: item.profitLossAmount || 0,
      }))
      loadStorageLocations()
    }
  } catch (error) {
    console.error('加载盘点单失败:', error)
    ElMessage.error('加载盘点单失败')
  }
}
</script>

<style scoped>
.inventory-count-create {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.warning-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  margin-bottom: 16px;
  background-color: #fdf6ec;
  border: 1px solid #f5dab1;
  border-radius: 4px;
  color: #e6a23c;
}

.summary-info {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-selection-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.search-section {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.content-section {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
}

.organization-tree {
  width: 250px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.tree-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
}

.user-list {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-user-tag {
  margin-left: auto;
}

.user-grid {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  align-content: start;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.user-item:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.user-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
  margin-right: 12px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 600;
  color: #303133;
}

.user-account {
  color: #909399;
  font-size: 12px;
}

.tree-node {
  display: inline-flex;
  align-items: center;
  padding: 4px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.readonly-input .el-input__wrapper) {
  background-color: #f5f7fa;
}
</style>

